package com.teangtang.fly.service;


import com.teangtang.fly.dto.CabinPriceDto;
import com.teangtang.fly.dto.FlightDto;
import com.teangtang.fly.dto.TicketDTO;
import com.teangtang.fly.entity.CabinPrice;
import com.teangtang.fly.entity.Flight;
import com.teangtang.fly.entity.Ticket;
import com.teangtang.fly.repository.TicketRepository;
import com.teangtang.fly.repository.FlightRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class FlightService {

    @Autowired
    private FlightRepository flightRepository;

    @Autowired
    private TicketRepository ticketRepository;

    public List<Flight> getAllFlight() {
        return flightRepository.findAll();
    }

    public Flight getFlightByFlightNumber(String flightNumber) {
        return flightRepository.findById(flightNumber).orElse(null);
    }
    public void deleteFlight(String flightNumber) {
        flightRepository.deleteById(flightNumber);
    }

    public Flight createFlight(Flight flight) {
        // 保存航班
//        flight = flightRepository.save(flight);

        // 生成后续的班次
        generateFlightSchedule(flight);
        return flight;
    }
    @Scheduled(cron = "0 0 0 * * *") // 每天凌晨执行一次
    public void generateFlights() {
        // 最近到达的航班
        Date currentTime = Date.from(Instant.now());
        Flight currentFlight = flightRepository.findClosestFlightByArrivalTime(currentTime);
        //生成后续的班次
        if(currentFlight != null){
            generateFlightSchedule(currentFlight);
        }
    }
    public void generateFlightSchedule(Flight newFlight) {
        // 获取航班的频率
        Long frequency = newFlight.getFrequency();

        // 获取航班的开始日期
        Date startDate = newFlight.getStartDate();

        // 计算结束日期
        Date endDate = calculateEndDate(startDate, frequency);

        // 根据频率和开始日期生成后续的班次
        generateFlightsByFrequency(newFlight, startDate, endDate);
    }

    private Date calculateEndDate(Date startDate, Long frequency) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        calendar.add(Calendar.DAY_OF_MONTH, 30);
        return calendar.getTime();
    }


    private void generateFlightsByFrequency(Flight newFlight, Date startDate, Date endDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        // 获取初始起飞时间
        Date lastDepartureTime = newFlight.getDepartureTime();

        while (calendar.getTime().before(endDate)) {
            // 创建新的航班对象
            Flight newFlightInstance = new Flight();

            // 复制航班信息
            newFlightInstance.setFlightNumber(newFlight.getFlightNumber());
            newFlightInstance.setCompanyName(newFlight.getCompanyName());
            newFlightInstance.setPlane(newFlight.getPlane());
            newFlightInstance.setAirline(newFlight.getAirline());
            newFlightInstance.setStatus(newFlight.getStatus());
            newFlightInstance.setFrequency(newFlight.getFrequency());
            newFlightInstance.setCabinPrices(newFlight.getCabinPrices());
            for (CabinPrice cabinPrice : newFlight.getCabinPrices()) {
                cabinPrice.setFlight(newFlightInstance);
            }
            newFlightInstance.setStartDate(calendar.getTime());

            // 生成航班 ID
            newFlightInstance.setFlightId(generateFlightId(newFlightInstance));

            // 计算新的起飞时间
            Calendar departureCalendar = Calendar.getInstance();
            departureCalendar.setTime(lastDepartureTime);
            departureCalendar.set(Calendar.YEAR, calendar.get(Calendar.YEAR));
            departureCalendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH));
            departureCalendar.set(Calendar.DAY_OF_MONTH, calendar.get(Calendar.DAY_OF_MONTH));
            newFlightInstance.setDepartureTime(departureCalendar.getTime());

            // 计算到达时间
            long durationInMillis = newFlight.getArrivalTime().getTime() - newFlight.getDepartureTime().getTime();
            Calendar arrivalCalendar = Calendar.getInstance();
            arrivalCalendar.setTime(newFlightInstance.getDepartureTime());
            arrivalCalendar.add(Calendar.MILLISECOND, (int) durationInMillis);
            newFlightInstance.setArrivalTime(arrivalCalendar.getTime());

            // 更新 lastDepartureTime
            lastDepartureTime = newFlightInstance.getDepartureTime();

            // 根据频率调整日期
            switch (newFlight.getFrequency().intValue()) {
                case 1: // 每天
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    break;
                case 2: // 隔天
                    calendar.add(Calendar.DAY_OF_MONTH, 2);
                    break;
                case 3: // 每周
                    calendar.add(Calendar.WEEK_OF_YEAR, 1);
                    break;
                case 4: // 每月
                    calendar.add(Calendar.MONTH, 1);
                    break;
                default:
                    throw new IllegalArgumentException("Invalid frequency value: " + newFlight.getFrequency());
            }

            List<Ticket> Tickets = new ArrayList<>();
            for (CabinPrice cabinPrice : newFlightInstance.getCabinPrices()) {
                for (int i = 0; i < cabinPrice.getCabin().getCapacity(); i++) {
                    Ticket ticket = new Ticket();
                    ticket.setFlight(newFlightInstance);
                    ticket.setSeatNumber(cabinPrice.getCabin().getName()+(i + 1));
                    ticket.setCabin(cabinPrice.getCabin());
                    ticket.setPrice(cabinPrice.getPrice());
                    ticket.setStatus("0");
                    Tickets.add(ticket);
                }
            }
            newFlightInstance.setTickets(Tickets);
            flightRepository.save(newFlightInstance);
        }
    }

    public List<FlightDto> turnFlightsToFlightDto(List<Flight> flights,int flag) {
        List<FlightDto> flightDtos = new ArrayList<>();
        for (Flight flight : flights) {
            FlightDto flightDto = new FlightDto();
            flightDto.setFlightId(flight.getFlightId());
            flightDto.setFlightNumber(flight.getFlightNumber());
            flightDto.setCompanyName(flight.getCompanyName());
            SimpleDateFormat webDepartureTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            flightDto.setWebDepartureTime(webDepartureTime.format(flight.getDepartureTime()));
            SimpleDateFormat webArrivalTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            flightDto.setWebArrivalTime(webArrivalTime.format(flight.getArrivalTime()));
            Long frequency = flight.getFrequency();
            if(frequency==1){
                flightDto.setWebFrequency("每天");
            }
            else if(frequency==2){
                flightDto.setWebFrequency("隔天");
            }
            else if(frequency==3){
                flightDto.setWebFrequency("每周");
            }
            else if(frequency==4){
                flightDto.setWebFrequency("每月");
            }
            String status = flight.getStatus();// 状态 0-待机 1-飞行中 2-已到达 3-延期 4-取消
            if(status.equals("0")){
                flightDto.setStatus("待机");
            }
            else if(status.equals("1")){
                flightDto.setStatus("飞行中");
            }
            else if(status.equals("2")){
                flightDto.setStatus("已到达");
            }
            else if(status.equals("3")){
                flightDto.setStatus("延期");
            }
            else if(status.equals("4")){
                flightDto.setStatus("取消");
            }
            flightDto.setPlane1(flight.getPlane().getId()+flight.getPlane().getName());
            flightDto.setAirline(flight.getAirline().getAirlineNumber());
            List<CabinPriceDto> cabinPrices = new ArrayList<>();
            for (CabinPrice cabinPrice : flight.getCabinPrices()) {
                CabinPriceDto cabinPriceDto = new CabinPriceDto();
                cabinPriceDto.setId(cabinPrice.getId());
                cabinPriceDto.setCabinName(cabinPrice.getCabin().getName());
                cabinPriceDto.setCabinType(cabinPrice.getCabin().getType());
                cabinPriceDto.setCapacity(cabinPrice.getCabin().getCapacity());
                cabinPriceDto.setPrice(cabinPrice.getPrice());
                cabinPrices.add(cabinPriceDto);
            }
            flightDto.setCabinPrices(cabinPrices);
            if(flag==1){
                List<TicketDTO> tickets = new ArrayList<>();
                for(Ticket ticket:flight.getTickets()){
                    TicketDTO ticketDTO = new TicketDTO();
                    ticketDTO.setId(ticket.getId());
                    ticketDTO.setSeatNumber(ticket.getSeatNumber());
                    ticketDTO.setPrice(ticket.getPrice());
                    if(ticket.getStatus().equals("0")){
                        ticketDTO.setStatus("待售");
                    }
                    else if(ticket.getStatus().equals("1")){
                        ticketDTO.setStatus("已售未检票");
                    }
                    else if(ticket.getStatus().equals("2")){
                        ticketDTO.setStatus("已检票");
                    }
                    else if(ticket.getStatus().equals("3")){
                        ticketDTO.setStatus("已被选中");
                    }
                    tickets.add(ticketDTO);
                }
                flightDto.setTickets(tickets);
            }
            flightDtos.add(flightDto);
        }
        return flightDtos;
    }
    public String generateFlightId(Flight flight) {
        // 获取航班号
        String flightNumber = flight.getFlightNumber();
        // 获取航班的开始日期
        Date startDate = flight.getStartDate();
        // 将日期格式化为字符串
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String dateString = dateFormat.format(startDate);
        // 生成航班 ID
        return flightNumber + dateString;
    }

}
